package com.shareyi.jshop.word.dataprocess;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class SimpleDataProcess
  implements DataProcess
{
	public Map<String, Object> processData(String dataSrc, boolean qutoflag) {
		HashMap<String,Object> map = new HashMap<String,Object>();
		List<List<String>> dataList = new ArrayList<List<String>>();

		String[] cols = dataSrc.split("\n");
		for (String col : cols) {
			col = col.trim();
			if (col.startsWith("##*"))
				continue;
			List<String> colList=this.getSplitStr(col,qutoflag);
			if(!colList.isEmpty()){
				dataList.add(colList);
			}
			
		}
		map.put("dataList", dataList);
		return map;
	}

  private List<String> getSplitStr(String col, boolean qutoflag) {
	  List<String> strList=new ArrayList<String>();
	  List<Integer> qutoIdxList=getQutoIdxList(col);
	  if(!qutoflag || qutoIdxList.isEmpty()){
		  String[] parts = col.split("[ \t]");
			LinkedList trimedLst = trimArray(parts);
			if (trimedLst.size() != 0){
				strList.addAll(trimedLst);
			}
	  }else{
		  
		
		  for(int i=0;i<qutoIdxList.size();i=i+2){
			  int qutoStartIdx=qutoIdxList.get(i);
			  
			  if(i==0&&qutoStartIdx!=0){
				  String startStr=col.substring(0,qutoStartIdx);
				  String[] parts = startStr.split("[ \t]");
					LinkedList trimedLst = trimArray(parts);
					if (trimedLst.size() != 0){
						strList.addAll(trimedLst);
					}
				  
			  }
			  
			  if(i+1==qutoIdxList.size()){ //引号为奇数个，到了最后一个了
				String strInQuto=col.substring(qutoStartIdx+1, col.length());
				strList.add(strInQuto);
				break;
			  }
			  int qutoEndIdx=qutoIdxList.get(i+1);
			  String strInQuto=col.substring(qutoStartIdx+1,qutoEndIdx );
			  strList.add(strInQuto);
			
			  int nextQutoStart=0;
			  if(i+2>=qutoIdxList.size()){ //如果下一个引号已经没有了
				  nextQutoStart=col.length();
			  }else{
				  nextQutoStart=qutoIdxList.get(i+2);
			  }
			 String strOutQuto=col.substring(qutoEndIdx+1, nextQutoStart);
			 String[] parts = strOutQuto.split("[ \t]");
				LinkedList trimedLst = trimArray(parts);
				if (trimedLst.size() != 0){
					strList.addAll(trimedLst);
				}
		  }
	  }
	  
	  return strList;
	}

private List<Integer> getQutoIdxList(String col) {
		List<Integer> list=new ArrayList<Integer>();
		int lastIdx=-1;
		while(true){
			int idx=col.indexOf('"', lastIdx+1);
			if(idx==-1){
				break;
			}else{
				if(idx!=0){
					if(col.charAt(idx-1)=='\\'){
						lastIdx=idx;
						continue;
					}
				}
				list.add(idx);
				lastIdx=idx;
			}
		}
		return list;
}

public static LinkedList<String> trimArray(String[] s1)
  {
    LinkedList ls = new LinkedList();
    for (int i = 0; i < s1.length; ++i)
    {
      if (s1[i] != null)
      {
        String trimed = s1[i].trim();
        if (trimed.length() != 0)
          ls.add(s1[i]);
      }
    }
    return ls;
  }

}